﻿
/****** Object:  User Defined Function dbo.DayOfWeek    Script Date: 10/14/2009 10:39:06 PM ******/

-- Returns the day of the week Monday=1 to Sunday = 7
CREATE function DayOfWeek( @InDate datetime ) 
returns int 
as 
begin
declare @DayOfWeek int
declare @FirstDayOfYear int
declare @DayOfYear int
 
set @DayOfYear = datepart( dayofyear, @InDate )

-- Get the first day of the year ( based on Monday rather than Sunday )
set @FirstDayOfYear = dbo.FirstDayOfYear(datepart(year, @InDate) ) - 1
if @FirstDayOfYear < 1  set @FirstDayOfYear = 7

set @DayOfWeek =  ( @DayOfYear + 5 + @FirstDayOfYear) %7  + 1

return( @DayOfWeek )
end

